/**
 * 验证用户登录的中间件
 */
module.exports = () => {
  return async function auth(ctx, next) {
    const token = ctx.get('Authorization')?.replace('Bearer ', '') || 
                  ctx.query.token || 
                  ctx.cookies.get('token');
    
    if (!token) {
      ctx.status = 401;
      ctx.body = {
        success: false,
        message: '未登录或登录已过期',
      };
      return;
    }
    
    // 验证token
    const isValid = ctx.service.user.verifyToken(token);
    
    if (!isValid) {
      ctx.status = 401;
      ctx.body = {
        success: false,
        message: '未登录或登录已过期',
      };
      return;
    }
    
    // 获取用户信息
    const sessionStore = ctx.app.sessionStore || new Map();
    ctx.user = sessionStore.get(token);
    
    await next();
  };
}; 